<template>
  <div class="p-6 space-y-4">
    <!-- 查询栏 -->
    <el-card shadow="never" class="rounded-lg">
      <div class="flex flex-col gap-4">
        <!-- 查询栏（与接口字段对齐） -->
        <el-form :model="filters" label-position="top" class="search-form" @keyup.enter="handleQuery">
          <el-row :gutter="12" align="bottom">
            <el-col :span="4">
              <el-form-item label="风险事件">
                <el-input v-model="filters.eventName" placeholder="请输入事件名称" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="设备">
                <el-select v-model="filters.equipmentId" placeholder="请选择设备" filterable clearable class="!w-full">
                  <el-option v-for="e in equipmentQueryOptions" :key="e.id" :label="e.sbmc" :value="e.sszz" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="原因">
                <el-input v-model="filters.reason" placeholder="请输入原因" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="后果">
                <el-input v-model="filters.result" placeholder="请输入后果" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="8" class="flex justify-end items-end gap-2">
              <el-button type="primary" :loading="queryLoading" @click="handleQuery">
                <el-icon class="mr-1"><Search /></el-icon>
                查询
              </el-button>
              <el-button :icon="Plus" @click="handleAdd">新增</el-button>
              <el-button :icon="Upload" @click="handleImport">导入</el-button>
              <el-button icon="Download" @click="handleExport">导出</el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </el-card>

    <!-- 列表表格 -->
    <el-card shadow="never" class="rounded-lg">
      <div v-loading="tableLoading">
        <el-table :data="tableData" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="序号" type="index" width="80" align="center" :index="indexMethod" />
          <el-table-column label="风险事件" prop="eventName" min-width="200" show-overflow-tooltip />
          <el-table-column label="设备" prop="equipmentName" min-width="160" show-overflow-tooltip />
          <el-table-column label="固有风险严重性" prop="inherentRiskSeverityName" min-width="140" align="center">
            <template #default="{ row }">
              <el-tag>{{ row.inherentRiskSeverityName || row.inherentRiskSeverity }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="残余风险严重性" prop="residualRiskSeverityName" min-width="140" align="center">
            <template #default="{ row }">
              <el-tag type="warning">{{ row.residualRiskSeverityName || row.residualRiskSeverity }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="原因" prop="reason" min-width="220" show-overflow-tooltip />
          <el-table-column label="防护措施" prop="measure" min-width="240" show-overflow-tooltip />
          <el-table-column label="措施监测指标" prop="indicatorNum" min-width="180" show-overflow-tooltip />
          <el-table-column label="后果" prop="result" min-width="240" show-overflow-tooltip />
          <el-table-column label="操作" width="140" align="center" fixed="right">
            <template #default="scope">
              <el-button link type="primary" @click="handleUpdate(scope.row)">编辑</el-button>
              <el-button link type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
          <template #empty>
            <el-empty description="暂无数据" />
          </template>
        </el-table>
      </div>

      <div class="flex items-center justify-between mt-4">
        <div class="text-gray-500">共{{ pagination.total }}条</div>
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 12, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
  <!-- 导入对话框 -->
  <el-dialog v-model="upload.open" :title="upload.title" width="420px" append-to-body>
    <el-upload
      ref="uploadRef"
      :limit="1"
      accept=".xlsx, .xls"
      :headers="upload.headers"
      :action="upload.url"
      :disabled="upload.isUploading"
      :on-progress="handleFileUploadProgress"
      :on-success="handleFileSuccess"
      :auto-upload="false"
      drag
    >
      <el-icon class="el-icon--upload">
        <i-ep-upload-filled />
      </el-icon>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <template #tip>
        <div class="text-center el-upload__tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">下载模板</el-link>
        </div>
      </template>
    </el-upload>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 新增/编辑对话框 -->
  <el-dialog v-model="dialog.visible" :title="dialog.title" width="780px" append-to-body>
    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
      <el-row :gutter="12">
        <el-col :span="12">
          <el-form-item label="风险事件" prop="eventName">
            <el-input v-model="form.eventName" placeholder="请输入风险事件" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备" prop="equipmentId">
            <el-select v-model="form.equipmentId" placeholder="请选择设备" filterable clearable>
              <el-option v-for="e in equipmentOptions" :key="e.id" :label="e.sbmc" :value="e.sszz" />
            </el-select>
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="固有风险可行性" prop="inherentRiskLikelihood">
            <el-input-number v-model="form.inherentRiskLikelihood" :min="0" :max="8" controls-position="right" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="固有风险严重性" prop="inherentRiskSeverity">
            <el-input-number v-model="form.inherentRiskSeverity" :min="0" :max="8" controls-position="right" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="残余风险可行性" prop="residualRiskLikelihood">
            <el-input-number v-model="form.residualRiskLikelihood" :min="0" :max="8" controls-position="right" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="残余风险严重性" prop="residualRiskSeverity">
            <el-input-number v-model="form.residualRiskSeverity" :min="0" :max="8" controls-position="right" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工艺位号" prop="indicatorNum">
            <el-input v-model="form.indicatorNum" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="原因" prop="reason">
            <el-input v-model="form.reason" type="textarea" :rows="2" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="防护措施" prop="measure">
            <el-input v-model="form.measure" type="textarea" :rows="2" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="后果" prop="result">
            <el-input v-model="form.result" type="textarea" :rows="2" />
          </el-form-item>
        </el-col>
        <!-- 将偏差一～偏差四移动到最后 -->
        <el-col :span="12">
          <el-form-item label="偏差一" prop="bias1"><el-input v-model="form.bias1" /></el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="偏差二" prop="bias2"><el-input v-model="form.bias2" /></el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="偏差三" prop="bias3"><el-input v-model="form.bias3" /></el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="偏差四" prop="bias4"><el-input v-model="form.bias4" /></el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" :loading="buttonLoading" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, getCurrentInstance, toRefs } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, Plus, Upload } from '@element-plus/icons-vue';
import { listAlarmRiskEvent, getAlarmRiskEvent, addAlarmRiskEvent, updateAlarmRiskEvent, delAlarmRiskEvent } from '@/api/system/alarmRiskEvent';
import type { AlarmRiskEventVO, AlarmRiskEventForm, AlarmRiskEventQuery } from '@/api/system/alarmRiskEvent/types';
import { listEquipment } from '@/api/system/equipment';
import { globalHeaders } from '@/utils/request';
import type { UploadFile } from 'element-plus';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const filters = reactive<Partial<AlarmRiskEventQuery>>({
  eventName: '',
  equipmentId: undefined,
  reason: '',
  result: ''
});

const queryLoading = ref(false);
const tableLoading = ref(false);
const buttonLoading = ref(false);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);

const pagination = reactive({
  currentPage: 1,
  pageSize: 12,
  total: 0
});

const tableData = ref<AlarmRiskEventVO[]>([]);

// 设备查询选项
const equipmentQueryOptions = ref<Array<{ id: string | number; sbmc: string; sszz: number }>>([]);

const indexMethod = (index: number) => (pagination.currentPage - 1) * pagination.pageSize + index + 1;

const fetchList = async (triggerLoading = true) => {
  if (triggerLoading) queryLoading.value = true;
  tableLoading.value = true;
  try {
    const query: AlarmRiskEventQuery = {
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
      eventName: filters.eventName,
      equipmentId: filters.equipmentId,
      reason: filters.reason,
      result: filters.result,
      params: {}
    } as any;
    const res = await listAlarmRiskEvent(query);
    tableData.value = res.rows || [];
    pagination.total = Number(res.total || 0);
  } catch (e) {
    ElMessage.error('数据加载失败，请稍后重试');
  } finally {
    tableLoading.value = false;
    queryLoading.value = false;
  }
};

const handleQuery = () => {
  pagination.currentPage = 1;
  fetchList();
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  fetchList(false);
};

const handleCurrentChange = (page: number) => {
  pagination.currentPage = page;
  fetchList(false);
};

const handleSelectionChange = (selection: AlarmRiskEventVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

// 新增/编辑
const formRef = ref();
const dialog = reactive<DialogOption>({ visible: false, title: '' });
const initFormData: AlarmRiskEventForm = {
  id: undefined,
  eventName: undefined,
  bias1: undefined,
  bias2: undefined,
  bias3: undefined,
  bias4: undefined,
  equipmentId: undefined,
  inherentRiskLikelihood: undefined,
  inherentRiskSeverity: undefined,
  residualRiskLikelihood: undefined,
  residualRiskSeverity: undefined,
  reason: undefined,
  measure: undefined,
  indicatorNum: undefined,
  result: undefined
};
const data = reactive<PageData<AlarmRiskEventForm, AlarmRiskEventQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 12
  } as any,
  rules: {
    eventName: [{ required: true, message: '请输入风险事件', trigger: 'blur' }],
    equipmentId: [{ required: true, message: '请选择设备', trigger: 'change' }],
    bias1: [{ required: true, message: '请输入偏差1', trigger: 'blur' }],
    bias2: [{ required: true, message: '请输入偏差2', trigger: 'blur' }],
    bias3: [{ required: true, message: '请输入偏差3', trigger: 'blur' }],
    bias4: [{ required: true, message: '请输入偏差4', trigger: 'blur' }],
    inherentRiskLikelihood: [{ required: true, message: '请输入固有风险可行性', trigger: 'change' }],
    inherentRiskSeverity: [{ required: true, message: '请输入固有风险严重性', trigger: 'change' }],
    residualRiskLikelihood: [{ required: true, message: '请输入残余风险可行性', trigger: 'change' }],
    residualRiskSeverity: [{ required: true, message: '请输入残余风险严重性', trigger: 'change' }],
    reason: [{ required: true, message: '请输入原因', trigger: 'blur' }],
    measure: [{ required: true, message: '请输入防护措施', trigger: 'blur' }],
    indicatorNum: [{ required: true, message: '请输入工艺位号', trigger: 'blur' }],
    result: [{ required: true, message: '请输入后果', trigger: 'blur' }]
  }
});
const { form, rules } = toRefs(data);

const equipmentOptions = ref<Array<{ id: string | number; sbmc: string; sszz: number }>>([]);
const loadEquipmentOptions = async () => {
  try {
    const res = await listEquipment({ pageNum: 1, pageSize: 200 } as any);
    equipmentOptions.value = (res.rows as any) || [];
  } catch (e) {
    equipmentOptions.value = [];
  }
};

// 加载设备查询选项（用于顶部筛选）
const loadEquipmentQueryOptions = async () => {
  try {
    const res = await listEquipment({ pageNum: 1, pageSize: 1000 } as any);
    equipmentQueryOptions.value = (res.rows as any) || [];
  } catch (e) {
    equipmentQueryOptions.value = [];
  }
};

const reset = () => {
  form.value = { ...initFormData };
  formRef.value?.resetFields?.();
};

const handleAdd = async () => {
  reset();
  await loadEquipmentOptions();
  dialog.visible = true;
  dialog.title = '新增风险事件';
};

const handleUpdate = async (row?: AlarmRiskEventVO) => {
  reset();
  await loadEquipmentOptions();
  const _id = row?.id || ids.value[0];
  const res = await getAlarmRiskEvent(_id);
  Object.assign(form.value, res.data);
  // 若后端仍返回设备 id，这里尝试映射为 sszz 以便下拉回显
  const matchedById = (equipmentOptions.value || []).find((e: any) => e.id === form.value.equipmentId);
  if (matchedById) {
    (form.value as any).equipmentId = matchedById.sszz;
  }
  dialog.visible = true;
  dialog.title = '编辑风险事件';
};

const submitForm = () => {
  (formRef.value as any)?.validate(async (valid: boolean) => {
    if (!valid) return;
    buttonLoading.value = true;
    try {
      if (form.value.id) {
        await updateAlarmRiskEvent(form.value);
      } else {
        await addAlarmRiskEvent(form.value);
      }
      ElMessage.success('操作成功');
      dialog.visible = false;
      await fetchList();
    } finally {
      buttonLoading.value = false;
    }
  });
};

const cancel = () => {
  dialog.visible = false;
  reset();
};

const handleDelete = async (row?: AlarmRiskEventVO) => {
  const _ids = row?.id || ids.value;
  await ElMessageBox.confirm(`是否确认删除编号为"${_ids}"的数据项？`, '提示', { type: 'warning' });
  await delAlarmRiskEvent(_ids);
  ElMessage.success('删除成功');
  await fetchList();
};

// 导出
const handleExport = () => {
  proxy?.download(
    'system/alarmRiskEvent/export',
    { ...filters, pageNum: undefined, pageSize: undefined },
    `alarm_risk_event_${new Date().getTime()}.xlsx`
  );
};

// 导入
const uploadRef = ref();
const upload = reactive<ImportOption>({
  open: false,
  title: '风险事件导入',
  isUploading: false,
  updateSupport: 0,
  headers: globalHeaders(),
  url: import.meta.env.VITE_APP_BASE_API + '/system/alarmRiskEvent/importData'
});
const handleImport = () => {
  upload.title = '风险事件导入';
  upload.open = true;
};
const importTemplate = () => {
  proxy?.download('system/alarmRiskEvent/downloadTemplate', {}, `alarm_risk_event_template_${new Date().getTime()}.xlsx`);
};
const handleFileUploadProgress = () => {
  upload.isUploading = true;
};
const handleFileSuccess = (response: any, file: UploadFile) => {
  upload.open = false;
  upload.isUploading = false;
  uploadRef.value?.handleRemove(file);
  ElMessage.success(response.msg || '导入完成');
  fetchList();
};
function submitFileForm() {
  uploadRef.value?.submit();
}

onMounted(async () => {
  await loadEquipmentQueryOptions();
  await fetchList(false);
});
</script>
